package org.tamal.jsf;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.tamal.Constants;

/**
 * This will validate whether the password is strong or not.
 * @author Tamal Kanti Nath
 */
@FacesValidator("EmailValidator")
public final class EmailValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) {
        String email = (String) value;
        if (isValid(email)) {
            return;
        }
        ResourceBundle rb = context.getApplication()
                .getResourceBundle(context, Constants.MSG);
        String message = component.getClientId() + ": "
                + rb.getString("login.email.invalid")
                    .replace("${email}", email);
        FacesMessage msg = new FacesMessage(message);
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        throw new ValidatorException(msg);
    }

    /**
     * Validate email address.
     * @param email Email id
     * @return true if valid
     */
    public static boolean isValid(String email) {
        if (email == null || email.isEmpty()) {
            return false;
        }
        return email.matches("[\\w\\.\\-_]+@[\\w\\.\\-]+\\.\\w+");
    }
}
